package com.nl.module_main.xiecheng

import kotlinx.coroutines.*
import java.util.concurrent.Executor
import java.util.concurrent.Executors
import kotlin.system.measureTimeMillis

/**
 * 作者: wangfei
 * 创建时期: 2022/12/1.
 * 包名: com.nl.module_main.xiecheng
 * 类名: NL_MedicaleEvaluation
 */
object Test01 {
    @JvmStatic
    fun main(args: Array<String>) {
        //test01()
        //test02()
        test03()
    }

    fun test01() = runBlocking {
        launch {
            delay(100)
            println("hello")
            delay(300)
            println("world")
        }
        println("test1")
        println("test2")
    }

    fun test02() = runBlocking {
        val job = launch {
            repeat(1000){
                println("job: test $it ...")
                delay(500L)
            }
        }
        delay(1300L)
        println("main: ready to cancel!")
        job.cancel() // 取消该作业
        job.join() // 等待作业执行结束
        println("main: Now cancel.")
    }

    fun test03() = runBlocking {
        var time = measureTimeMillis {
            val a = async(Dispatchers.IO) {
                printWithThreadInfo("111")
                delay(1000)
                1
            }
            val b = async(Dispatchers.IO){
                printWithThreadInfo("222")
                delay(2000)
                2
            }
            printWithThreadInfo("当前时间:${a.await() + b.await()}")
            printWithThreadInfo("end")
        }
        printWithThreadInfo("时间$time")
    }

    private fun printWithThreadInfo(value:String? = null){
        println(Thread.currentThread().name + "==work== $value")
    }

    //CoroutineScope
    val dispacher = Executors.newFixedThreadPool(1).asCoroutineDispatcher()

    val handle = CoroutineExceptionHandler { coroutineContext, throwable ->
        printWithThreadInfo("exceptionHandler: throwable: $throwable")
    }

    val myScope = CoroutineScope(dispacher + handle);

}